package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.account.enums.CodeEnum;
import com.ruoyi.account.util.HttpResult;
import com.ruoyi.account.util.PaPayUtil;
import com.ruoyi.account.util.UniversalCamelCaseConverter;
import com.ruoyi.system.util.BusinessException;

import java.util.HashMap;
import java.util.Map;

public class BasePaServiceImpl {


    public JSONObject handleError(HttpResult httpResult) {
        if (httpResult.getStatus() == 500){
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), httpResult.getError());
        }
        JSONObject obj = JSON.parseObject(httpResult.getBody());
        JSONObject extenddata = obj.getJSONObject(PaPayUtil.extenddata) == null ? obj.getJSONObject(PaPayUtil.edata) : obj.getJSONObject(PaPayUtil.extenddata);

        if (extenddata.get(PaPayUtil.code) != null && !extenddata.getString(PaPayUtil.code).equals(PaPayUtil.code_000000)) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), extenddata.getString(PaPayUtil.TXN_RETURN_MSG));
        }
        if (extenddata.get(PaPayUtil.TXN_RETURN_CODE) != null && !extenddata.getString(PaPayUtil.TXN_RETURN_CODE).equals(PaPayUtil.code_000000)) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), extenddata.getString(PaPayUtil.TXN_RETURN_MSG));
        }
        return extenddata;
    }

    public JSONObject buildResult(JSONObject json) {
        return UniversalCamelCaseConverter.convertKeys(json);
    }

    protected Map<String, String> buildOrderReq(String requestParams) {
        Map<String, String> map = new HashMap<>();
        String[] arry = requestParams.split("&");
        for (int i = 0; i < arry.length; i++) {
            String[] arr = arry[i].split("=");
            if (arr.length == 2) {
                map.put(arr[0], arr[1]);
            } else {
                map.put(arr[0], "");
            }
        }
        return map;
    }

}
